<template>
    <div>
   <van-address-list
  v-model="chosenAddressId"
  :list="list"
  :disabled-list="disabledList"
  disabled-text="以下地址超出配送范围"
  default-tag-text="默认"
  @add="onAdd"
  @edit="onEdit"  
  @select="selected"
/>  
    </div>
   
</template>

<script>
import { ref, watch } from 'vue';
import { Toast } from 'vant';
import { useRouter} from 'vue-router'
import { useStore } from 'vuex'
import {fetchaddress} from '@/API/goods.js'

export default {
  props:{
      fromshop:{
        type : String
      }
  },
  setup() {
    const chosenAddressId = ref(1);
    const router = useRouter()
     const store = useStore()
     console.log(store.state.userInfo.id);
   const list = ref([])
   const cheaked =ref("")
     list.value = [
      {
        id: '1',
        name: '张三',
        tel: '13000000000',
        address: '浙江省杭州市西湖区文三路 138 号东方通信大厦 7 楼 501 室',
        isDefault: true,
      },
      {
        id: '2',
        name: '李四',
        tel: '1310000000',
        address: '浙江省杭州市拱墅区莫干山路 50 号',
      },
      {
        id: '3',
        name: '李五',
        tel: '131000',
        address: '干山路 50 号',
        city:"张家口",
        country:"万全区",
        province:'河北省',
        areaCode:"130000-130700-130708"

      },
    ];
    const disabledList = [
      {
        id: '3',
        name: '王五',
        tel: '1320000000',
        address: '浙江省杭州市滨江区江南大道 15 号',
      },
    ];
    const freshen = async () =>{

        let result = await fetchaddress(store.state.userInfo.id)
        list.value=  result.map(item =>{
          item.isDefault !==0 ? chosenAddressId.value=item.id  : "" 
      item.address = item.province+item.city+item.country+item.addressDetail+","+item.postalCode
            return item
        })
       
        let addresslocal = JSON.parse( localStorage.getItem('addresslocal') || '{}' )
        if(Object.keys(addresslocal).length !=0){
          chosenAddressId.value =   addresslocal.id
        }
        let index =  list.value.findIndex(item => item.isDefault ==1)
        list.value.unshift(list.value[index])
        list.value.splice(index+1,1)
        console.log(result);
        console.log("list",list.value);
    };
    freshen()

    const onAdd = () => router.push("/addAddress");
    const onEdit = (item, index) => router.push('/editaddress/'+ JSON.stringify(item));
    // const onEdit = (item, index) => console.log(item,index);

    return {
      list,
      onAdd,
      onEdit,
      disabledList,
      chosenAddressId,
      cheaked,
      freshen
    };
  },
  methods:{
    selected(item,index){
      if(this.fromshop){
           localStorage.setItem('addresslocal',JSON.stringify(item))
             this.$router.back()
      }

     
      
    }
  },
 activated(){
       this.freshen()
  }  
};

</script>

<style lang="scss" scoped>
.a{
  background-color: #fff;
}
</style>